document.addEventListener('DOMContentLoaded', function() {
    // 获取DOM元素
    const qrTextInput = document.getElementById('qr-text');
    const qrTitleInput = document.getElementById('qr-title');
    const foregroundColorInput = document.getElementById('foreground-color');
    const backgroundColorInput = document.getElementById('background-color');
    const dotStyleSelect = document.getElementById('dot-style');
    const logoSelect = document.getElementById('logo-select');
    const generateBtn = document.getElementById('generate-btn');
    const downloadBtn = document.getElementById('download-btn');
    const qrDisplayTitle = document.getElementById('qr-display-title');
    const qrcodeContainer = document.getElementById('qrcode');
    const themeButtons = document.querySelectorAll('.theme-btn');
    const qrWrapper = document.querySelector('.qr-wrapper');
    
    // QR码配置
    let qrConfig = {
        text: '',
        title: '',
        foreground: '#000000',
        background: '#ffffff',
        dotStyle: 'square',
        logo: 'none',
        theme: 'classic',
        customLogo: null
    };
    
    // 主题样式定义
    const themes = {
        classic: {
            foreground: '#000000',
            background: '#ffffff',
            dotStyle: 'square',
            theme: 'classic'
        },
        blue: {
            foreground: '#1e88e5',
            background: '#ffffff',
            dotStyle: 'rounded',
            theme: 'blue'
        },
        flower: {
            foreground: '#e91e63',
            background: '#ffffff',
            dotStyle: 'dots',
            logo: 'flower',
            theme: 'flower'
        },
        elegant: {
            foreground: '#ad8a56',
            background: '#ffffff',
            dotStyle: 'classy',
            theme: 'elegant'
        },
        neon: {
            foreground: '#7289da',
            background: '#0f0f1e',
            dotStyle: 'classy-rounded',
            theme: 'neon'
        },
        // 新增主题
        cyberpunk: {
            foreground: '#ff2a6d',
            background: '#05d9e8',
            dotStyle: 'classy-rounded',
            theme: 'cyberpunk'
        },
        galaxy: {
            foreground: '#5d4af4',
            background: '#000000',
            dotStyle: 'dots',
            theme: 'galaxy'
        },
        gradient: {
            foreground: '#ff9a8b',
            background: '#ffffff',
            dotStyle: 'rounded',
            theme: 'gradient'
        }
    };
    
    // 加载Logo资源
    const logoResources = {
        flower: "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'%3E%3Cpath fill='%23e91e63' d='M50,10 C60,30 85,35 90,50 C85,65 60,70 50,90 C40,70 15,65 10,50 C15,35 40,30 50,10 Z'/%3E%3Ccircle fill='%23ffeb3b' cx='50' cy='50' r='10'/%3E%3C/svg%3E",
        star: "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'%3E%3Cpath fill='%23ffc107' d='M50,10 L61,36 L90,40 L70,60 L75,90 L50,75 L25,90 L30,60 L10,40 L39,36 Z'/%3E%3C/svg%3E",
        heart: "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'%3E%3Cpath fill='%23f44336' d='M50,90 C85,65 90,35 75,20 C60,5 50,30 50,30 C50,30 40,5 25,20 C10,35 15,65 50,90 Z'/%3E%3C/svg%3E"
    };
    
    // 初始化
    function init() {
        // 监听输入变化
        qrTextInput.addEventListener('input', updateConfigAndGenerateQR);
        qrTitleInput.addEventListener('input', updateConfigAndGenerateQR);
        foregroundColorInput.addEventListener('input', updateConfigAndGenerateQR);
        backgroundColorInput.addEventListener('input', updateConfigAndGenerateQR);
        dotStyleSelect.addEventListener('change', updateConfigAndGenerateQR);
        logoSelect.addEventListener('change', handleLogoSelectChange);
        
        // 监听按钮点击
        generateBtn.addEventListener('click', generateQRCode);
        downloadBtn.addEventListener('click', downloadQRCode);
        
        // 主题按钮点击事件
        themeButtons.forEach(btn => {
            btn.addEventListener('click', function() {
                applyTheme(this.dataset.theme);
                
                // 更新活动按钮样式
                themeButtons.forEach(b => b.classList.remove('active'));
                this.classList.add('active');
                
                // 应用主题后自动生成二维码
                generateQRCode();
            });
        });
        
        // 处理自定义Logo上传
        const customLogoUpload = document.getElementById('custom-logo-upload');
        const fileUploadBtn = document.getElementById('file-upload-btn');
        const fileName = document.getElementById('file-name');
        
        if (customLogoUpload && fileUploadBtn && fileName) {
            fileUploadBtn.addEventListener('click', function() {
                customLogoUpload.click();
            });
            
            customLogoUpload.addEventListener('change', function(e) {
                if (e.target.files && e.target.files[0]) {
                    const file = e.target.files[0];
                    fileName.textContent = file.name;
                    handleCustomLogoUpload(file);
                }
            });
        }
        
        // 初始化界面
        applyTheme('classic');
        themeButtons[0].classList.add('active');
    }
    
    // 处理Logo选择变化
    function handleLogoSelectChange() {
        const selectedValue = logoSelect.value;
        const logoUploadContainer = document.getElementById('logo-upload-container');
        
        if (selectedValue === 'custom') {
            logoUploadContainer.style.display = 'flex';
        } else {
            logoUploadContainer.style.display = 'none';
            updateConfigAndGenerateQR();
        }
    }
    
    // 更新配置并生成二维码
    function updateConfigAndGenerateQR() {
        updateConfig();
        
        // // 如果已经有输入文本，则自动生成二维码
        // if (qrConfig.text) {
        //     generateQRCode();
        // }
    }
    
    // 更新配置
    function updateConfig() {
        qrConfig.text = qrTextInput.value;
        qrConfig.title = qrTitleInput.value;
        qrConfig.foreground = foregroundColorInput.value;
        qrConfig.background = backgroundColorInput.value;
        qrConfig.dotStyle = dotStyleSelect.value;
        qrConfig.logo = logoSelect.value;
        
        // 更新显示标题
        qrDisplayTitle.textContent = qrConfig.title;
    }
    
    // 应用主题
    function applyTheme(themeName) {
        const theme = themes[themeName];
        if (!theme) return;
        
        // 更新表单值
        foregroundColorInput.value = theme.foreground;
        backgroundColorInput.value = theme.background;
        dotStyleSelect.value = theme.dotStyle;
        
        if (theme.logo) {
            logoSelect.value = theme.logo;
        }
        
        // 更新配置
        qrConfig.theme = theme.theme;
        qrConfig.foreground = theme.foreground;
        qrConfig.background = theme.background;
        qrConfig.dotStyle = theme.dotStyle;
        if (theme.logo) qrConfig.logo = theme.logo;
        
        // 更新wrapper类
        qrWrapper.className = 'qr-wrapper ' + theme.theme;
    }
    
    // 处理自定义Logo上传
    function handleCustomLogoUpload(file) {
        const reader = new FileReader();
        reader.onload = function(e) {
            qrConfig.customLogo = e.target.result;
            qrConfig.logo = 'custom';
            
            // 上传图片后自动重新生成二维码
            generateQRCode();
        };
        reader.readAsDataURL(file);
    }
    
    // 生成二维码
    function generateQRCode() {
        if (!qrConfig.text) {
            alert('请输入内容后再生成二维码');
            return;
        }
        
        // 清空容器
        qrcodeContainer.innerHTML = '';
        
        // 使用QRCode.js生成二维码
        const qrcode = new QRCode(qrcodeContainer, {
            text: qrConfig.text,
            width: 200,
            height: 200,
            colorDark: qrConfig.foreground,
            colorLight: qrConfig.background,
            correctLevel: QRCode.CorrectLevel.H
        });
        
        // 添加点的样式
        setTimeout(() => {
            const qrImg = qrcodeContainer.querySelector('img');
            if (qrImg) {
                applyQRStyles(qrImg);
                
                // 添加Logo (如果有)
                if (qrConfig.logo === 'custom' && qrConfig.customLogo) {
                    addCustomLogoToQR(qrImg, qrConfig.customLogo);
                } else if (qrConfig.logo && qrConfig.logo !== 'none') {
                    addLogoToQR(qrImg);
                }
                
                // 启用下载按钮
                downloadBtn.disabled = false;
            }
        }, 100);
    }
    
    // 添加样式到QR码
    function applyQRStyles(qrImg) {
        const canvas = document.createElement('canvas');
        const ctx = canvas.getContext('2d');
        const img = new Image();
        
        img.onload = function() {
            canvas.width = img.width;
            canvas.height = img.height;
            
            // 绘制背景
            ctx.fillStyle = qrConfig.background;
            ctx.fillRect(0, 0, canvas.width, canvas.height);
            
            // 获取二维码数据
            const imageData = getQRImageData(img);
            
            // 根据点的样式绘制
            drawQRDots(ctx, imageData, canvas.width, canvas.height);
            
            // 替换原图像
            qrImg.src = canvas.toDataURL();
        };
        
        img.src = qrImg.src;
    }
    
    // 获取QR码图像数据
    function getQRImageData(img) {
        const tempCanvas = document.createElement('canvas');
        const tempCtx = tempCanvas.getContext('2d');
        tempCanvas.width = img.width;
        tempCanvas.height = img.height;
        
        tempCtx.drawImage(img, 0, 0);
        return tempCtx.getImageData(0, 0, img.width, img.height);
    }
    
    // 根据样式绘制QR点
    function drawQRDots(ctx, imageData, width, height) {
        const data = imageData.data;
        const dotSize = Math.floor(width / 25); // 估计每个点的大小
        
        // 清除画布
        ctx.clearRect(0, 0, width, height);
        ctx.fillStyle = qrConfig.background;
        ctx.fillRect(0, 0, width, height);
        
        // 特殊主题效果
        if (qrConfig.theme === 'gradient') {
            const gradient = ctx.createLinearGradient(0, 0, width, height);
            gradient.addColorStop(0, '#ff9a8b');
            gradient.addColorStop(0.5, '#ff6b95');
            gradient.addColorStop(1, '#ff8177');
            ctx.fillStyle = gradient;
            ctx.fillRect(0, 0, width, height);
        } else if (qrConfig.theme === 'galaxy') {
            // 绘制星空背景
            ctx.fillStyle = '#000000';
            ctx.fillRect(0, 0, width, height);
            
            // 绘制随机星星
            for (let i = 0; i < 100; i++) {
                const x = Math.random() * width;
                const y = Math.random() * height;
                const r = Math.random() * 1.5;
                const opacity = Math.random() * 0.8 + 0.2;
                
                ctx.beginPath();
                ctx.arc(x, y, r, 0, Math.PI * 2);
                ctx.fillStyle = `rgba(255, 255, 255, ${opacity})`;
                ctx.fill();
            }
        }
        
        // 遍历图像数据
        for (let y = 0; y < height; y += dotSize) {
            for (let x = 0; x < width; x += dotSize) {
                const idx = (y * width + x) * 4;
                // 如果是黑色点(二维码数据)
                if (data[idx] < 128) {
                    drawDot(ctx, x, y, dotSize);
                }
            }
        }
    }
    
    // 绘制单个点
    function drawDot(ctx, x, y, size) {
        const halfSize = size / 2;
        const centerX = x + halfSize;
        const centerY = y + halfSize;
        const radius = size / 2;
        
        // 特殊主题效果
        if (qrConfig.theme === 'cyberpunk') {
            // 随机选择颜色
            const colors = ['#ff2a6d', '#05d9e8', '#d1f7ff'];
            const randomIndex = Math.floor(Math.random() * 10) % 3;
            ctx.fillStyle = colors[randomIndex];
        } else if (qrConfig.theme === 'galaxy') {
            // 为星空主题创建发光效果
            const grd = ctx.createRadialGradient(
                centerX, centerY, 0,
                centerX, centerY, radius
            );
            grd.addColorStop(0, '#5d4af4');
            grd.addColorStop(1, '#413bd1');
            ctx.fillStyle = grd;
        } else if (qrConfig.theme === 'gradient') {
            ctx.fillStyle = qrConfig.foreground;
        } else {
            ctx.fillStyle = qrConfig.foreground;
        }
        
        switch (qrConfig.dotStyle) {
            case 'square':
                ctx.fillRect(x, y, size, size);
                break;
            case 'rounded':
                ctx.beginPath();
                ctx.roundRect(x, y, size, size, radius / 2);
                ctx.fill();
                break;
            case 'dots':
                ctx.beginPath();
                ctx.arc(centerX, centerY, radius * 0.8, 0, Math.PI * 2);
                ctx.fill();
                break;
            case 'classy':
                ctx.beginPath();
                if ((x / size) % 3 === 0 || (y / size) % 3 === 0) {
                    ctx.fillRect(x, y, size, size);
                } else {
                    ctx.moveTo(x, y + halfSize);
                    ctx.lineTo(x + halfSize, y);
                    ctx.lineTo(x + size, y + halfSize);
                    ctx.lineTo(x + halfSize, y + size);
                    ctx.closePath();
                    ctx.fill();
                }
                break;
            case 'classy-rounded':
                ctx.beginPath();
                if ((x / size) % 3 === 0 || (y / size) % 3 === 0) {
                    ctx.roundRect(x, y, size, size, radius / 3);
                } else {
                    ctx.arc(centerX, centerY, radius * 0.7, 0, Math.PI * 2);
                }
                ctx.fill();
                break;
        }
    }
    
    // 添加Logo到QR码
    function addLogoToQR(qrImg) {
        const logoUrl = logoResources[qrConfig.logo];
        if (!logoUrl) return;
        
        const canvas = document.createElement('canvas');
        const ctx = canvas.getContext('2d');
        const img = new Image();
        
        img.onload = function() {
            canvas.width = img.width;
            canvas.height = img.height;
            
            // 绘制QR码
            ctx.drawImage(img, 0, 0);
            
            // 加载Logo
            const logoImg = new Image();
            logoImg.onload = function() {
                // 计算Logo大小和位置
                const logoSize = img.width * 0.2;
                const logoX = (img.width - logoSize) / 2;
                const logoY = (img.height - logoSize) / 2;
                
                // 绘制白色背景
                ctx.fillStyle = 'white';
                ctx.beginPath();
                ctx.arc(logoX + logoSize/2, logoY + logoSize/2, logoSize/2 + 2, 0, Math.PI * 2);
                ctx.fill();
                
                // 绘制Logo
                ctx.drawImage(logoImg, logoX, logoY, logoSize, logoSize);
                
                // 更新QR码图像
                qrImg.src = canvas.toDataURL();
            };
            logoImg.src = logoUrl;
        };
        
        img.src = qrImg.src;
    }
    
    // 添加自定义Logo到QR码
    function addCustomLogoToQR(qrImg, customLogoDataUrl) {
        const canvas = document.createElement('canvas');
        const ctx = canvas.getContext('2d');
        const img = new Image();
        
        img.onload = function() {
            canvas.width = img.width;
            canvas.height = img.height;
            
            // 绘制QR码
            ctx.drawImage(img, 0, 0);
            
            // 加载Logo
            const logoImg = new Image();
            logoImg.onload = function() {
                // 计算Logo大小和位置
                const logoSize = img.width * 0.2;
                const logoX = (img.width - logoSize) / 2;
                const logoY = (img.height - logoSize) / 2;
                
                // 绘制白色背景
                ctx.fillStyle = 'white';
                ctx.beginPath();
                ctx.arc(logoX + logoSize/2, logoY + logoSize/2, logoSize/2 + 2, 0, Math.PI * 2);
                ctx.fill();
                
                // 绘制Logo
                ctx.drawImage(logoImg, logoX, logoY, logoSize, logoSize);
                
                // 更新QR码图像
                qrImg.src = canvas.toDataURL();
            };
            logoImg.src = customLogoDataUrl;
        };
        
        img.src = qrImg.src;
    }
    
    // 下载二维码
    function downloadQRCode() {
        const qrImg = qrcodeContainer.querySelector('img');
        if (!qrImg) return;
        
        // 创建一个新的画布来组合二维码和标题
        const canvas = document.createElement('canvas');
        const ctx = canvas.getContext('2d');
        const padding = 20;
        let titleHeight = 0;
        
        // 如果有标题，计算标题高度
        if (qrConfig.title) {
            ctx.font = 'bold 20px Arial';
            titleHeight = 40;
        }
        
        // 设置画布大小
        canvas.width = qrImg.width + (padding * 2);
        canvas.height = qrImg.height + (padding * 2) + titleHeight;
        
        // 绘制背景
        ctx.fillStyle = qrConfig.background;
        ctx.fillRect(0, 0, canvas.width, canvas.height);
        
        // 如果有标题，绘制标题
        if (qrConfig.title) {
            ctx.fillStyle = qrConfig.foreground;
            ctx.font = 'bold 20px Arial';
            ctx.textAlign = 'center';
            ctx.fillText(qrConfig.title, canvas.width / 2, padding + 20);
        }
        
        // 绘制二维码
        ctx.drawImage(qrImg, padding, padding + titleHeight, qrImg.width, qrImg.height);
        
        // 创建下载链接
        const link = document.createElement('a');
        const filename = qrConfig.title ? `${qrConfig.title}-qrcode.png` : 'qrcode.png';
        
        link.download = filename;
        link.href = canvas.toDataURL('image/png');
        link.click();
    }
    
    // 修复可能不支持的roundRect方法 (某些旧版浏览器)
    if (!CanvasRenderingContext2D.prototype.roundRect) {
        CanvasRenderingContext2D.prototype.roundRect = function(x, y, width, height, radius) {
            if (width < 2 * radius) radius = width / 2;
            if (height < 2 * radius) radius = height / 2;
            this.beginPath();
            this.moveTo(x + radius, y);
            this.arcTo(x + width, y, x + width, y + height, radius);
            this.arcTo(x + width, y + height, x, y + height, radius);
            this.arcTo(x, y + height, x, y, radius);
            this.arcTo(x, y, x + width, y, radius);
            this.closePath();
            return this;
        };
    }
    
    // 初始化
    init();
}); 